package com.nakamachizu.controller.cron;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import java.util.logging.Logger;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;

import com.google.appengine.api.datastore.Key;
import com.nakamachizu.meta.session.MixiFriendSessionMeta;
import com.nakamachizu.meta.session.MixiSessionDataMeta;
import com.nakamachizu.model.mixi.FriendMapModel;
import com.nakamachizu.model.session.MixiFriendSession;

public class CleanMixiController extends Controller {

    private static final Logger log = Logger.getLogger(CleanMixiController.class.getName());
        
    @Override
    public Navigation run() throws Exception {
        Calendar now = Calendar.getInstance(TimeZone.getTimeZone("Asia/Tokyo"));
        MixiSessionDataMeta meta = MixiSessionDataMeta.get();
        List<Key>list = Datastore.query(meta).filter(meta.expireDate.lessThan(now.getTime())).asKeyList();
        if(list != null){
            log.info("削除対象mixiセッション" + Integer.toString(list.size()) + "件です。");
            Datastore.delete(list);
            log.info("削除対象mixiセッション" + Integer.toString(list.size()) + "件の削除が完了しました。");
        }
        
        MixiFriendSessionMeta mfsm = MixiFriendSessionMeta.get();
        List<MixiFriendSession>mfsList = Datastore.query(mfsm).filter(mfsm.expireDate.lessThan(now.getTime())).asList();
        if(mfsList != null && mfsList.size() > 0){
            list = new ArrayList<Key>();
            
            log.info("削除対象mixiFriendセッション" + Integer.toString(mfsList.size()) + "件です。");
            
            for(MixiFriendSession mfs : mfsList){
                list.add(mfs.getKey());
                
                List<FriendMapModel> fmmList = mfs.getFriendMapModelListRef().getModelList();
                for(FriendMapModel fmm : fmmList){
                    list.add(fmm.getKey());
                }
            }
            
            Datastore.delete(list);
            log.info("削除対象mixiFriendセッション" + Integer.toString(mfsList.size()) + "件の削除が完了しました。");
        }
        
        return null;
    }
}
